package com.ruoyi.backend.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.backend.dto.Map3dServerWithMinioDTO;
import com.ruoyi.backend.dto.Map3dServerWithRGBDTO;
import com.ruoyi.common.utils.http.HttpUtils;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Map3dServer相关工具类
 */
public class Map3ServerUtils {

    private static final Logger logger = LoggerFactory.getLogger(Map3ServerUtils.class);

    /**
     * 从minio获取文件到本地并进行RGB融合后上传到minio
     */
    @SneakyThrows
    public boolean UploadFromMinioAndRGBMerge(String fileName, String bands) throws RuntimeException {
        MinioUtil minioUtil = new MinioUtil();

        // 下载文件
        String tifFileLocalUrl = downloadFileFromMinio(fileName);
        if (tifFileLocalUrl.isEmpty()) {
            logger.error("map3d-server从minio中获取文件失败: {}", fileName);
            return false;
        }

        // RGB融合
        String dstLocalFilePath = mergeRGBBands(tifFileLocalUrl, bands);
        if (dstLocalFilePath.isEmpty()) {
            logger.error("map3d-server进行RGB融合失败: {}", tifFileLocalUrl);
            return false;
        }

        // 上传文件到Minio
        return uploadFileToMinio(dstLocalFilePath, fileName, minioUtil);
    }

    /**
     * 从Minio下载文件到本地
     * @author whx
     */
    private String downloadFileFromMinio(String fileName) {
        Map3dServerWithMinioDTO map3dServerWithMinioDTO = new Map3dServerWithMinioDTO();
        map3dServerWithMinioDTO.setAction("download");
        map3dServerWithMinioDTO.setObjectName(fileName);

        String sendParam = buildParamString(
                "action", map3dServerWithMinioDTO.getAction(),
                "endPoint", map3dServerWithMinioDTO.getEndPoint(),
                "accessKey", map3dServerWithMinioDTO.getAccessKey(),
                "secretKey", map3dServerWithMinioDTO.getSecretKey(),
                "bucketName", map3dServerWithMinioDTO.getBucketName(),
                "pathKey", map3dServerWithMinioDTO.getPathKey(),
                "objectName", map3dServerWithMinioDTO.getObjectName()
        );

        String response = HttpUtils.sendPost("http://localhost:7000/miniotools", sendParam);
        JSONObject jsonObject = JSON.parseObject(response);
        String tifFileLocalUrl = jsonObject.getString("data");

        if (tifFileLocalUrl == null || !tifFileLocalUrl.contains(map3dServerWithMinioDTO.getPathKey())) {
            return "";
        }
        return tifFileLocalUrl;
    }

    /**
     * 进行RGB融合
     * @author whx
     */
    private String mergeRGBBands(String tifFileLocalUrl, String bands) {
        Map3dServerWithRGBDTO map3dServerWithRGBDTO = new Map3dServerWithRGBDTO();
        map3dServerWithRGBDTO.setAction("muiltsbandstif2png");
        map3dServerWithRGBDTO.setFileUrl(tifFileLocalUrl);
        map3dServerWithRGBDTO.setBands(bands);

        String sendParam = buildParamString(
                "action", map3dServerWithRGBDTO.getAction(),
                "fileUrl", map3dServerWithRGBDTO.getFileUrl(),
                "bands", map3dServerWithRGBDTO.getBands(),
                "dstPath", map3dServerWithRGBDTO.getDstPath()
        );

        String response = HttpUtils.sendPost("http://localhost:7000/ecologytools", sendParam);
        JSONObject jsonObject = JSON.parseObject(response);
        return jsonObject.getString("path");
    }

    private boolean uploadFileToMinio(String dstLocalFilePath, String fileName, MinioUtil minioUtil) throws IOException {
        File file = new File(dstLocalFilePath);
        if (!file.exists() || !file.isFile()) {
            throw new RuntimeException("本地不存在相关文件: " + dstLocalFilePath);
        }

        MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), null, new FileInputStream(file));
        String minioUploadInformation = minioUtil.uploadFile("backend", "rgb-" + fileName.replace(".tif", ".png"), multipartFile);

        return !minioUploadInformation.isEmpty();
    }

    /**
     * 构建参数字符串
     * @param params 参数键值对数组
     * @return 拼接后的参数字符串
     */
    private String buildParamString(String... params) {
        StringBuilder paramBuilder = new StringBuilder();
        for (int i = 0; i < params.length; i += 2) {
            if (i > 0) {
                paramBuilder.append("&");
            }
            paramBuilder.append(params[i]).append("=").append(params[i + 1]);
        }
        return paramBuilder.toString();
    }


}